﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mani.Common.Security;
using RastinArgham.CRM.Business;
using Mani.Common;

namespace RastinArgham.CRM.Web
{
    public partial class list_stock_items : System.Web.UI.Page
    {
        public ISecurityManager securityManager { get; set; }
        public CRMRepository crmRepository { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (securityManager == null)
            {
                securityManager = new SecurityManager();
                securityManager.authProvider = new WebAuthorizationProvider();
            }

            if (crmRepository == null)
                crmRepository = new CRMRepository();


            if (!securityManager.IsActionPermitted("stock_items"))
                Response.Redirect("~/access_denied.aspx");

            if (!Page.IsPostBack)
            {
                LoadProducts();
                LoadAgents();
                LoadStates();
                SearchStockItems();
            }
        }

        private void LoadProducts()
        {
            ddlProducts.DataSource = crmRepository.GetProducts();
            ddlProducts.DataBind();
        }

        private void LoadAgents()
        {
            List<aspnet_Users> agents = securityManager.FindUsersByRole("agents");
            ddlAgents.DataSource = agents;
            ddlAgents.DataBind();

            ddlAssignAgents.DataSource = agents;
            ddlAssignAgents.DataBind();
        }
 
        private void LoadStates()
        {
            ddlState.DataSource = crmRepository.GetStockItemStates();
            ddlState.DataBind();
        }

        private void SearchStockItems()
        {
            List<StockItem> stockItems = new List<StockItem>();

            if (!String.IsNullOrEmpty(txtSerialNumber.Text))
            {
                StockItem s = crmRepository.GetStockItemBySerial(txtSerialNumber.Text);
                if ( s != null )
                    stockItems.Add(s);
            }
            else if (ddlAgents.SelectedValue != "-1")
                stockItems = crmRepository.GetStockItemsByAssignedTo(new Guid(ddlAgents.SelectedValue));
            else if (ddlProducts.SelectedValue != "-1" && ddlState.SelectedValue != "-1")
                stockItems = crmRepository.GetStockItemsByProductAndState(Convert.ToInt32(ddlState.SelectedValue), Convert.ToInt32(ddlProducts.SelectedValue));
            else if (ddlProducts.SelectedValue != "-1")
                stockItems = crmRepository.GetStockItemsByProduct(Convert.ToInt32(ddlProducts.SelectedValue));
            else if (ddlState.SelectedValue != "-1")
                stockItems = crmRepository.GetStockItemsByState(Convert.ToInt32(ddlState.SelectedValue));
            else
                stockItems = crmRepository.GetAllStockItems();

            lblCount.Text = stockItems.Count.ToString();
            gvStockItems.DataSource = stockItems;
            gvStockItems.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            SearchStockItems();
        }

        protected void gvStockItems_PageIndexChanged(object sender, EventArgs e)
        {

        }

        protected void gvStockItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvStockItems.PageIndex = e.NewPageIndex;
            SearchStockItems();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            List<StockItem> items = new List<StockItem>();

            string[] serials = txtListSerials.Text.Split(',');

            if (serials.Length < 1)
            {
                UIHelper.ClientAlert(this, "لطفا لیست سریال های مورد نظر خود را با کاما جدا کرده و وارد کنید.");
                return;
            }

            foreach (string s in serials)
            {
                StockItem stockItem = crmRepository.GetStockItemBySerial(s);
                if (stockItem == null)
                {
                    UIHelper.ClientAlert(this, String.Format("یکی از سریال های وارد شده در بانک اطلاعاتی یافت نشد : " + "{0}", s));
                    return;
                }

                if (stockItem.Status != (int)StockItemStates.InStock)
                {
                    UIHelper.ClientAlert(this, String.Format("برای تخصیص کالا به نماینده، کالا باید در وضعیت در انبار باشد این سریال در این وضعیت نمی باشد : " + "{0}", s));
                    return;
                }

                items.Add(stockItem);
            }

            foreach (var item in items)
            {
                item.Status = (int)StockItemStates.AssignedToAgent;
                item.AssignedTo = new Guid(ddlAssignAgents.SelectedValue);
                item.LastUpdate = DateTime.Now;
                item.OperatorId = securityManager.authProvider.GetCurrentUser().UserId;
            }

            crmRepository.Save();
            
            UIHelper.ClientAlert(this, "تغییرات با موفقیت ذخیره شده");
            ClearForm();
            SearchStockItems();
        }

        private void ClearForm()
        {
            txtListSerials.Text = String.Empty;
            ddlAssignAgents.ClearSelection();
        }
    }
}